<template>
    <div class="jianzhan-content">
        <Crumb name="Purchase Order"></Crumb>
        <div class="content">
            <Search>
                <el-input
                        v-model="key"
                        size="small"
                        class="input"
                        placeholder="Search By RequestNo"
                        prefix-icon="el-icon-search"
                ></el-input>
                <el-button
                        size="small"
                        type="primary"
                >Search
                </el-button>
            </Search>
            <div class="table-wrapper">
                <el-table
                        :data="poList.slice((pageNum-1)*pageSize,pageNum*pageSize)"
                        border
                        stripe
                        style="width: 100%">
                    <el-table-column
                            type="index"
                            label="No"
                            width="100"
                    >
                    </el-table-column>

                    <el-table-column
                            prop="purchaseNo"
                            label="Purchase Number"
                            width="150"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="supplierName"
                            label="Vendor Name"
                            width="150">
                    </el-table-column>
                    <el-table-column
                            prop="duty"
                            label="PPN/Duty"

                    />
                    <el-table-column
                            prop="freight"
                            label="Delivery Fee"
                    />
                    <el-table-column
                            prop="bagging"
                            label="Package Fee"

                    />
                    <el-table-column
                            prop="otherCost"
                            label="Other"

                    />
                    <el-table-column label="Opr" width="210">
                        <template slot-scope="scope">
                            <el-button
                                    size="mini"
                                    @click="openEdit(scope.row)">Request
                            </el-button>
                            <el-button
                                    size="mini"
                                    @click="
                                    supplierId = scope.row.supplierId
                                    visible = true
                                     ">Po History
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page">
                    <el-pagination background
                                   :page-size="pageSize"
                                   @current-change="changePage"
                                   layout="prev, pager, next"
                                   :total="total"/>
                </div>

            </div>

            <div class="modal-wrapper">
                <el-dialog
                        title="Purchase Order"
                        :visible.sync="dialogVisible"
                        width="80%"
                >
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="200px" class="demo-ruleForm"
                             :inline="true">
                        <el-form-item label="Duty／PPN">
                            <el-input v-model="ruleForm.duty"/>
                        </el-form-item>
                        <el-form-item label="Delivery Fee">
                            <el-input v-model="ruleForm.freight"/>
                        </el-form-item>
                        <el-form-item label="Package Fee">
                            <el-input v-model="ruleForm.bagging"/>
                        </el-form-item>
                        <el-form-item label="Other Fee">
                            <el-input v-model="ruleForm.otherCost"/>
                        </el-form-item>
                    </el-form>
                    <el-table
                            :data="partList"
                            border
                            stripe
                            style="width: 100%">
                        <el-table-column
                                type="index"
                                prop="no"
                                label="No"
                                width="180"
                        />

                        <el-table-column
                                prop="partsNumber"
                                label="Part No"
                                width="180"/>
                        <el-table-column
                                prop="denomination"
                                label="Description"
                                width="320"/>
                        <el-table-column label="Qty" width="180" prop="quantity"/>
                        <el-table-column label="Price">
                            <template slot-scope="scope">
                                {{scope.row.purchasePrice}}
                            </template>
                        </el-table-column>
                        <el-table-column label="Total Price">
                            <template slot-scope="scope">
                                {{scope.row.purchasePrice * scope.row.quantity}}
                            </template>
                        </el-table-column>
                    </el-table>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">Cancel</el-button>
                        <el-button type="primary" @click="submitForm">Confirm</el-button>
                        <el-button type="warning" @click="convert">Convert Po</el-button>
                    </span>
                </el-dialog>
                <el-dialog
                        title="Purchase Order"
                        :visible.sync="dialogVisible1"
                        width="80%"
                >
                    <el-table
                            :data="partList"
                            border
                            stripe
                            style="width: 100%">
                        <el-table-column
                                type="index"
                                prop="no"
                                label="No"
                                width="180"
                        />

                        <el-table-column
                                prop="partsNumber"
                                label="Part No"
                                width="180"/>
                        <el-table-column
                                prop="denomination"
                                label="Description"
                                width="320"/>
                        <el-table-column label="Qty" width="180" prop="quantity"/>
                        <el-table-column label="Price">
                            <template slot-scope="scope">
                                {{scope.row.purchasePrice}}
                            </template>
                        </el-table-column>
                        <el-table-column label="Total Price">
                            <template slot-scope="scope">
                                {{scope.row.purchasePrice * scope.row.quantity}}
                            </template>
                        </el-table-column>
                    </el-table>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible1 = false">Cancel</el-button>
                    </span>
                </el-dialog>
                <po-history :supplierId="supplierId" :visible="visible" @close="visible=false" @detail="showDetail"/>
            </div>
        </div>
    </div>
</template>

<script>
    import Crumb from '@/components/common/crumb'
    import Search from '@/components/common/search'
    import poHistory from '@/components/purchase/poHistory'
    import {ERROR_OK} from "../../util/config";
    import mixins from '../../util/mixins'
    import {getPurchaseOrder, getPoDetail, submitPo} from "../../api/purchase";

    export default {
        name: "purchase-order",
        mixins:[mixins],
        data() {
            return {
                visible: false,
                supplierId: null,
                list: [],
                ruleForm: {
                    id: '',
                    duty: '',
                    freight: '',
                    bagging: '',
                    otherCost: ''
                },
                rules: {
                    title: [
                        {required: true, message: 'Title is required', trigger: 'blur'},
                    ],
                    vendorName: [
                        {required: true, message: 'Name is required', trigger: 'blur'}
                    ],
                    business: [
                        {required: true, message: 'Business is required', trigger: 'blur'}
                    ],
                    address: [
                        {required: true, message: 'Address is required', trigger: 'blur'}
                    ],
                },
                partList: [],
                key: '',
                dialogVisible: false,
                dialogVisible1: false,
            }
        },
        computed: {
            poList() {
                return this.list.filter(item => {
                    return item.purchaseNo.indexOf(this.key) > -1
                })
            }
        },
        created() {
            this._getPoList()
        },
        mounted() {
            this.$nextTick(() => {
                import('../../util/pdf.js').then(model => {
                    this.pdf = model.default;
                })
            })
        },
        methods: {
            convert() {
                let body = [
                    [
                        {text: 'No', alignment: 'center'},
                        {text: 'Part No', alignment: 'center'},
                        {text: 'description', colSpan: 2, style: 'tableHeader', alignment: 'center'},
                        {},
                        {text: 'Rate', style: 'tableHeader', alignment: 'center'},
                        {text: 'Qty', colSpan: 2, style: 'tableHeader', alignment: 'center'},
                        {},
                        {text: 'Line Total', style: 'tableHeader', alignment: 'center'},
                    ],
                    [
                        {text: '序号', style: 'tableHeader', alignment: 'center'},
                        {text: '配件编号', style: 'tableHeader', alignment: 'center'},
                        {text: '中文描述', style: 'tableHeader', alignment: 'center'},
                        {text: '英文描述', style: 'tableHeader', alignment: 'center'},
                        {text: '单价', style: 'tableHeader', alignment: 'center'},
                        {text: '数量', style: 'tableHeader', alignment: 'center'},
                        {text: '单位', style: 'tableHeader', alignment: 'center'},
                        {text: '总计', style: 'tableHeader', alignment: 'center'}
                    ],
                    // [{text: 'Service Item',colSpan:4, style: 'tableHeader', alignment: 'left'},{},{},{},{text: 'Service Fee',colSpan:4, style: 'tableHeader', alignment: 'left'},{},{},{}]
                ];
                const mainBody = this.partList.map((item, index) => {
                    return [index + 1, item.partsNumber, item.denomination, item.designation, item.purchasePrice, item.quantity, 'pc', item.purchasePrice * item.quantity]
                });
                body = body.concat(mainBody);
                let total = 0;
                mainBody.forEach(item => {
                    total += item[7]
                });

                let doc = {
                    filename: 'QO',
                    pageSize: 'LEGAL',
                    pageMargins: [10, 200, 10, 60],
                    header: [
                        {
                            margin: [20, 20, 20, 20],
                            columns: [
                                {
                                    width: '70%',
                                    text: [
                                        {
                                            text: 'PT INDONESIA EQUIPMENT LINE\n',
                                            style: 'header'
                                        },
                                        {
                                            text: "Leading in Service Innovation\n",
                                            style: 'subTitle'
                                        },
                                        ' No.17-18 Blok A, Ruko Inkopal Kelapa Gading \n',
                                        ' Jl. Boulevard Barat Raya Jakarta Utara 14240 Indonesia \n',
                                        ' Tel: 0800-1581212'
                                    ],

                                },
                                {
                                    width: '*',
                                    text: 'Purchase Order',
                                    style: 'title',
                                    alignment: 'right'
                                }
                            ],
                        },
                        {
                            margin: [20, -10, 0, 20],
                            columns: [
                                {
                                    width: 50,
                                    text: 'Bill To:'
                                },
                                {
                                    width: '60%',
                                    text: [
                                        `Vendor: ${this.ruleForm.supplierName}\n`,
                                        'Address: NO.17-18 Blok A,Ruko Inkopal\n kelapa gading jl.boulevard bvarat raya jukarta\n',
                                        'Contact Person : Jack Anderson\n',
                                        'Contact Number: 69888545'
                                    ]
                                },
                                {
                                    width: '*',
                                    text: [
                                        `Date: ${this.ruleForm.requestDate}\n`,
                                        `PO.No: ${this.ruleForm.purchaseNo}\n`,
                                        'Shipment fee : Exclude\n',
                                        'Payment: COD'
                                    ]
                                }
                            ]
                        }
                    ],
                    content: [
                        {
                            layout: 'lightHorizontalLines',
                            alignment: 'center',
                            table: {
                                widths: ['auto', 'auto', 120, 120, 'auto', 'auto', 'auto', 'auto'],
                                headerRows: 2,
                                // keepWithHeaderRows: 1,
                                body: body
                            }
                        },
                        {
                            margin: [20, 20, 20, 20],
                            columns: [
                                {
                                    width: '50%',
                                    text: [
                                        ' Make all checks payable to\n',
                                        // 'A/N: PT. INDONESIA EQUIPMENT LINE\n',
                                        // 'NO.: 0653700722\n',
                                        // 'BANK CENTRAL ASIA KCU KELAPA GADING'
                                    ]
                                },
                                {
                                    width: '*',
                                    text: [
                                        `Sub Total: ${total}\n`,
                                        `Delivery Fee: ${this.ruleForm.freight}\n`,
                                        `Packaging Fee: ${this.ruleForm.bagging}\n`,
                                        `PPN: ${this.ruleForm.duty}\n`,
                                        `other: ${this.ruleForm.otherCost}`
                                        // {
                                        //     text:'Total Inc PPN',
                                        //     alignment:'center',
                                        //     style:{
                                        //         background:'#ddd'
                                        //     }
                                        // }
                                    ]
                                }
                            ]
                        }
                    ],
                    footer: [
                        {
                            text: 'If you have any questions or concerns, please contact 0800-1581212',
                            width: '100%',
                            alignment: 'center'
                        },
                        {text: 'THANK YOU FOR YOUR BUSINESS! ', width: '100%', alignment: 'center'}
                    ],

                    defaultStyle: {
                        font: 'msyh'
                    },

                    styles: {
                        header: {
                            fontSize: 15,
                            bold: true
                        },
                        title: {
                            fontWeight: 'light',
                            fontSize: 25,
                            bold: false
                        },
                        subTitle: {
                            fontSize: 12,
                            bold: true,
                            italic: true
                        }
                    }

                }
                this.pdf.open(doc);
            },
            async _getPoList() {
                const {status, data} = await getPurchaseOrder();
                if (status === ERROR_OK) {
                    this.list = data
                }
            },

            submitForm() {
                this.$refs.ruleForm.validate(async (valid) => {
                    if (valid) {
                        const {
                            id,
                            duty,
                            freight,
                            bagging,
                            otherCost
                        } = this.ruleForm;
                        const {status,data,msg} = await submitPo({id,duty,freight,bagging,otherCost});
                        if(status === ERROR_OK) {
                            this.$notify({
                                title:'Success',
                                message:data,
                            });
                            this._getPoList()
                        } else {
                            this.$message({
                                message:msg,
                                type:'error'
                            })
                        }
                        this.dialogVisible = false

                    }
                });
            },
            clear() {
                this.ruleForm.vendorName = '';
                this.ruleForm.no = '';
                this.ruleForm.customerName = '';
                this.ruleForm.business = '';
                this.ruleForm.address = '';
                this.ruleForm.city = '';
                this.ruleForm.contact = '';
                this.ruleForm.phone = '';
                this.ruleForm.note = '';
            },
            openAdd() {
                this.clear();
                this.dialogVisible = true
            },
            showDetail(r) {
                const partList = r.sparePurchaseHistoryDetailList.map(item => {
                    return {
                        ...item.spareParts,
                        quantity: item.quantity,
                        stockQuantity: item.stockQuantity,
                        purchasePrice: item.purchasePrice,
                    }
                });
                this.partList = partList;
                this.dialogVisible1 = true
            },
            async openEdit(r) {
                let {status, data} = await getPoDetail(r.id || r.no);
                if (status === ERROR_OK) {
                    const partList = data.sparePurchaseDetailVoList.map(item => {
                        return {
                            ...item.spareParts,
                            quantity: item.quantity,
                            stockQuantity: item.stockQuantity,
                            purchasePrice: item.purchasePrice,
                        }
                    });
                    this.partList = partList;
                    this.ruleForm = data;
                    this.dialogVisible = true
                }
            }
        },
        watch: {
            poList(list) {
                this.total = list.length
            }
        },
        components: {
            Crumb, Search, poHistory
        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";
        .content {
           @include content
        }
</style>